package command

import (
	"fmt"
	"os"

	"code.google.com/p/microtool/basic/dialect"
	"code.google.com/p/microtool/basic/scanner"
)

// The reformat command runs the lexical analyzer over the input file and
// produces pretty-printed output.
var reformat = &Command{
	Name: "reformat",
	Info: "Produce a pretty-printed version of the input.",
	Fn:   reformatImpl,
}

// reformatImpl implements the reformat command.
func reformatImpl(input, dialec string) error {
	d := dialect.Active[dialec]
	if d == nil {
		return fmt.Errorf("Unknown BASIC dialect: %q", dialec)
	}
	r, err := os.Open(input)
	if err != nil {
		return err
	}
	s, err := scanner.NewScanner(r, d)
	if err != nil {
		return err
	}

	var line []*scanner.Token
	for t := s.Next(); t.Type != scanner.TypeEOF; t = s.Next() {
		if t.Type == scanner.TypeNewline {
			output(line)
			line = nil
			continue
		}
		line = append(line, t)
	}
	return nil
}

func output(ts []*scanner.Token) {
	for i, t := range ts {
		if i > 0 && !scanner.NoSpace[scanner.TypePair{ts[i-1].Type, t.Type}] {
			fmt.Print(" ")
		}
		fmt.Print(t.String())
	}
	fmt.Println()
}
